<template>
  <div class="cart-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>🛒 我的购物车</h1>
      
      <el-button type="primary" @click="$router.push('/')" icon="ShoppingCart">
        继续点餐
      </el-button>
    </div>

    <!-- 空购物车状态 -->
    <el-empty v-if="cartItems.length === 0" description="购物车空空如也">
      <div class="empty-actions">
        <el-button type="primary" @click="$router.push('/')">去点餐</el-button>
        <el-button 
          type="success" 
          @click="$router.push('/orders')"
          :disabled="true"
        >
          查看我的订单
        </el-button>
      </div>
    </el-empty>

    <!-- 有商品的购物车 -->
    <div v-else>
      <!-- 购物车商品列表 -->
      <el-card class="cart-card">
        <template #header>
          <div class="card-header">
            <span>购物车商品</span>
            <el-button type="danger" @click="clearCart" plain size="small">
              清空购物车
            </el-button>
          </div>
        </template>

        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="商品" width="300">
            <template #default="{ row }">
              <div class="product-info">
                <el-image 
                  :src="row.image" 
                  :alt="row.name"
                  fit="cover"
                  class="product-image"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="product-details">
                  <div class="product-name">{{ row.name }}</div>
                  <div class="product-desc">{{ row.description }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="120" align="center">
            <template #default="{ row }">
              <span class="price">¥{{ row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="150" align="center">
            <template #default="{ row }">
              <div class="quantity-controls">
                <el-button 
                  :disabled="row.quantity <= 1" 
                  @click="decreaseQuantity(row.id)"
                  icon="Minus"
                  size="small"
                />
                <el-input-number 
                  v-model="row.quantity" 
                  :min="1" 
                  :max="99"
                  size="small"
                  @change="updateQuantity(row)"
                  controls-position="right"
                  class="quantity-input"
                />
                <el-button 
                  @click="increaseQuantity(row.id)"
                  icon="Plus"
                  size="small"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120" align="center">
            <template #default="{ row }">
              <span class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="80" align="center">
            <template #default="{ row }">
              <el-button 
                type="danger" 
                @click="removeItem(row.id)" 
                icon="Delete"
                size="small"
                link
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 价格汇总 -->
      <el-card class="summary-card">
        <div class="summary-content">
          <div class="summary-item">
            <span>商品小计:</span>
            <span class="amount">¥{{ subtotal.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>配送费:</span>
            <span class="amount">¥{{ deliveryFee.toFixed(2) }}</span>
          </div>
          <el-divider />
          <div class="summary-item total">
            <span>总计:</span>
            <span class="total-amount">¥{{ total.toFixed(2) }}</span>
          </div>

          <div class="checkout-actions">
            <el-button 
              type="primary" 
              size="large" 
              @click="checkout"
              class="checkout-btn"
            >
              立即结算
            </el-button>
            <el-button 
              type="success" 
              size="large" 
              @click="$router.push('/orders')"
              class="view-orders-btn"
            >
              查看我的订单
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Delete, Plus, Minus, ShoppingCart } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 购物车数据
interface CartItem {
  id: number
  name: string
  price: number
  quantity: number
  image?: string
  description?: string
}

const cartItems = ref<CartItem[]>([])

// 计算属性
const subtotal = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
})

const deliveryFee = computed(() => {
  return subtotal.value > 0 ? 5 : 0
})

const total = computed(() => {
  return subtotal.value + deliveryFee.value
})

// 生命周期
onMounted(() => {
  loadCart()
})

// 方法
const loadCart = () => {
  console.log('正在加载购物车数据...')
  const savedCart = localStorage.getItem('cart')
  console.log('从localStorage获取的数据:', savedCart)
  
  if (savedCart) {
    try {
      cartItems.value = JSON.parse(savedCart)
      console.log('解析后的购物车数据:', cartItems.value)
    } catch (error) {
      console.error('解析购物车数据失败:', error)
      // 使用示例数据
      cartItems.value = getSampleCartData()
    }
  } else {
    console.log('localStorage中没有购物车数据，使用示例数据')
    cartItems.value = getSampleCartData()
  }
  
  console.log('最终购物车数据:', cartItems.value)
}

// 添加示例数据函数
const getSampleCartData = (): CartItem[] => [
  {
    id: 1,
    name: '土豆丝',
    price: 12,
    quantity: 2,
    image: new URL('@/assets/images/土豆丝.jpg', import.meta.url).href,
    description: '香辣可口'
  },
  {
    id: 2,
    name: '西湖醋鱼',
    price: 88,
    quantity: 1,
    image: new URL('@/assets/images/西湖醋鱼.jpg', import.meta.url).href,
    description: '杭州名菜，酸甜可口'
  }
]

const saveCart = () => {
  localStorage.setItem('cart', JSON.stringify(cartItems.value))
  // 触发购物车更新事件
  window.dispatchEvent(new CustomEvent('cartUpdated'))
}

const increaseQuantity = (itemId: number) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item) {
    item.quantity++
    saveCart()
  }
}

const decreaseQuantity = (itemId: number) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item && item.quantity > 1) {
    item.quantity--
    saveCart()
  }
}

const updateQuantity = (item: CartItem) => {
  if (item.quantity < 1) {
    item.quantity = 1
  }
  saveCart()
}

const removeItem = (itemId: number) => {
  cartItems.value = cartItems.value.filter(item => item.id !== itemId)
  saveCart()
  ElMessage.success('商品已移除')
}

const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    cartItems.value = []
    saveCart()
    ElMessage.success('购物车已清空')
  } catch {
    // 用户取消
  }
}

const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车是空的，请先添加商品！')
    return
  }

  ElMessageBox.confirm(`总计: ¥${total.value.toFixed(2)}，确认结算吗？`, '确认订单', {
    confirmButtonText: '确认支付',
    cancelButtonText: '再想想',
    type: 'success'
  }).then(() => {
    // 创建订单并跳转到订单页面
    createOrderFromCart()
  }).catch(() => {
    // 用户取消
  })
}

// 从购物车创建订单
const createOrderFromCart = () => {
  const order = {
    id: Date.now(),
    orderNumber: `ORD${Date.now()}`,
    items: [...cartItems.value],
    subtotal: subtotal.value,
    deliveryFee: deliveryFee.value,
    totalAmount: total.value,
    status: 'pending' as const,
    createTime: new Date().toISOString()
  }

  // 保存订单到localStorage
  const existingOrders = JSON.parse(localStorage.getItem('orders') || '[]')
  existingOrders.unshift(order)
  localStorage.setItem('orders', JSON.stringify(existingOrders))

  // 清空购物车
  cartItems.value = []
  saveCart()
  
  // 触发订单更新事件
  window.dispatchEvent(new CustomEvent('ordersUpdated'))
  
  ElMessage.success('下单成功！请及时支付')
  router.push('/orders')
}
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  color: #303133;
  margin: 0;
}

.empty-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.cart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.product-desc {
  font-size: 12px;
  color: #909399;
}

.price {
  color: #e74c3c;
  font-weight: 600;
}

.subtotal {
  color: #e74c3c;
  font-weight: 600;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-input {
  width: 80px;
}

.summary-card {
  max-width: 400px;
  margin-left: auto;
}

.summary-content {
  padding: 0 12px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
}

.summary-item.total {
  font-size: 16px;
  font-weight: 600;
}

.amount {
  color: #606266;
}

.total-amount {
  color: #e74c3c;
  font-size: 18px;
}

.checkout-actions {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.checkout-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
}

.view-orders-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
}
</style>